<template>
  <div class="params">
    <!-- 面包屑导航 -->
    <breadcrumb :breadcrumb="breadcrumb"></breadcrumb>
    <el-card class="box-card content">
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false"></el-alert>

      <div class="params_banner">
        <span class="params_text">选择商品分类：</span>
        <!-- 分类--联级选择器 -->
        <el-cascader v-model="selectedKey" :options="cateLIst" :props="props" clearable></el-cascader>

        <!-- Tabs 标签页 -->
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <!-- 传参：only ===获取静态属性 -->
          <el-tab-pane label="静态属性" name="only"></el-tab-pane>
          <!--传参:many ===获取动态参数 -->
          <el-tab-pane label="动态参数" name="many"></el-tab-pane>
        </el-tabs>

        <!-- 下面tag切换内容 -->
        <div class="tagConten">
          <!-- 按钮 -->
          <el-button
            @click="addParams"
            :disabled="isDisabled"
            size="mini"
            type="primary"
          >{{tagBtnName}}</el-button>
          <!-- 表格 -->
          <el-table :data="tableData" border style="width: 100%">
            <!-- 展开项 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 便签 -->
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 便签输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  size="small"
                  ref="saveTagInput"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 便签添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 序号项 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作" width="180">
              <template v-slot="scope">
                <el-button @click="editParams(scope.row)" size="mini" type="primary">编辑</el-button>
                <el-button size="mini" @click="delParams(scope.row)" type="danger">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 弹框---添加/编辑 -->
        <el-dialog :title="title+addParamsTitle" @close="clear" :visible.sync="paramsDialogVisible">
          <el-form>
            <el-form-item :label="`${addParamsTitle}:`" :label-width="formLabelWidth">
              <el-input v-model="addParamsName" autocomplete></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="paramsDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addOrEditParams">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>
           
<script>
export default {
  name: "params",
  data() {
    return {
      breadcrumb: ["商品管理", "分类参数"],
      // 商品分类数据一级、二级、三级分类
      cateLIst: [],
      // 选中的商品分类
      selectedKey: [],
      // 级联选择器配置内容
      props: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      // Tabs 标签页默认选项
      activeName: "only",
      // 获取的参数---静态属性
      onlyData: [],
      // 获取的参数---动态参数
      manyData: [],
      // 弹框显示与隐藏
      paramsDialogVisible: false,
      // 新增/修改
      addParamsName: "",
      // 暂时存储
      tsName: "",
      // 属性id
      attrId: 0,
      formLabelWidth: "80px",
      title: "", //拼接字符串  添加/修改
      // 显示名称
      addParamsTitle: ""
    };
  },
  created() {
    this.getCategoriesList();
  },
  methods: {
    // 初始化---渲染联级选择器选项
    async getCategoriesList() {
      const { data: res } = await this.$http.get("/categories");
      this.cateLIst = res.data;
    },
    // tag切换
    handleTabClick() {
      //在选择无改变时。 可以判断以前是否有数据  减少服务器请求数
      if (this.selectedKey.length != 0) {
        this.getAttributes(this.cateId, this.activeName);
      }
    },

    // 获取参数列表---公用函数
    async getAttributes(id, sel) {
      const { data: res } = await this.$http.get(
        `categories/${id}/attributes`,
        { params: { sel } }
      );
      if (sel == "only") {
        //  如果是静态属性  先处理数据
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
          // 增加属性
          item.inputVisible = false;
          item.inputValue = "";
        });
        // 在赋值数据
        this.onlyData = res.data;
      } else {
        //  如果是动态参数
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
          // 增加属性
          item.inputVisible = false;
          item.inputValue = "";
        });

        this.manyData = res.data;
      }
    },
    // 显示增加弹框---渲染标题
    addParams() {
      this.title = "添加";
      this.addParamsTitle = this.activeName == "only" ? "静态属性" : "动态参数";
      this.paramsDialogVisible = true;
    },
    // 显示编辑弹框---渲染标题及内容
    editParams(data) {
      this.title = "修改";
      this.addParamsTitle = this.activeName == "only" ? "静态属性" : "动态参数";
      // 保存名字
      this.addParamsName = data.attr_name;
      // 暂存，，用于判断是否有修改
      this.tsName = data.attr_name;
      // 保存属性id
      this.attrId = data.attr_id;
      //  显示弹框
      this.paramsDialogVisible = true;
    },
    // 添加或编辑处理函数
    async addOrEditParams() {
      if (this.title == "添加") {
        // 做新增--判断是否有内容
        if (this.addParamsName == "")
          return this.$message.error("您还没有输入名称！");
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_sel: this.activeName,
            attr_name: this.addParamsName,
            attr_vals: "a,b,c"
          }
        );
        if (res.meta.status == 201) {
          this.$message.success(res.meta.msg);
          this.paramsDialogVisible = false;
          // 重新加载
          this.getAttributes(this.cateId, this.activeName);
        }
      } else if (this.title == "修改") {
        // 做编辑
        if (this.addParamsName == "" || this.addParamsName === this.tsName)
          return this.$message.error("输入为空或无任何修改！");
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.attrId}`,
          {
            attr_sel: this.activeName,
            attr_name: this.addParamsName,
            attr_vals: "a,b,c"
          }
        );
        if (res.meta.status == 200) {
          this.$message.success(res.meta.msg);
          this.paramsDialogVisible = false;
          this.getAttributes(this.cateId, this.activeName);
        }
      } else {
        return false;
      }
    },
    // 删除参数
    async delParams(data) {
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${data.attr_id}`
      );
      if (res.meta.status == 200) {
        this.$message.success(res.meta.msg);
        this.getAttributes(this.cateId, this.activeName);
      }
    },
    // 弹框关闭时清除输入框的内容
    clear() {
      this.attrId = 0;
      this.addParamsName = "";
      this.tsName = "";
      this.title = "";
      this.addParamsTitle = "";
    },
    // 显示可添加的tag便签
    showInput(row) {
      // console.log(row);
      // 将属性存在自己的每行的对象中
      row.inputVisible = true;
      // 让输入框自动获取焦点
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 输入参数展开行的tag便签
    handleInputConfirm(row) {
      if (row.inputValue.trim() == "") {
        this.$message.error("你还没输入内容");
        row.inputVisible = false;
      } else {
        // 将新增内容增加到数组中
        row.attr_vals.push(row.inputValue.trim());
        //  调用处理函数
        this.setTagFun(row);
      }
    },
    // tag便签的新增或删除的数据请求
    async setTagFun(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(",")
        }
      );
      if (res.meta.status == 200) {
        this.$message.success(res.meta.msg);
        row.inputValue = "";
        row.inputVisible = false;
      }
    },
    // 删除参数展开行的tag便签
    handleClose(i, row) {
      // 根据索引，删除对应的tag便签
      row.attr_vals.splice(i, 1);
      this.setTagFun(row);
    }
  },
  // 设置属性
  computed: {
    // 设置添加按钮是否禁用
    isDisabled() {
      return this.selectedKey.length !== 3;
    },
    // 设置添加按钮的名字
    tagBtnName() {
      return this.activeName == "only" ? "添加属性" : "添加参数";
    },
    // 设置表格加载的内容
    tableData() {
      return this.activeName == "only" ? this.onlyData : this.manyData;
    },
    // 获取选中的三级分类id
    cateId() {
      if (this.selectedKey.length === 3) {
        return this.selectedKey[this.selectedKey.length - 1];
      }
      return null;
    }
  },

  // 监听选择框值的变化
  watch: {
    selectedKey() {
      // 判断选择框是否有内容，===判断是否有id值
      if (this.cateId != null) {
        // 有则加载参数或者属性
        this.getAttributes(this.cateId, this.activeName);
      } else {
        // 没有则清空表格数据
        this.onlyData = [];
        this.manyData = [];
        return false;
      }
    }
  }
};
</script>
<style scoped lang='less'>
.params {
  width: 100%;
  height: 100%;
  .content {
    padding: 10px 20px;
    background-color: #fff;
    margin-top: 10px;
    border-radius: 8px;
    .params_banner {
      margin-top: 10px;
      .params_text {
        font-size: 18px;
      }
      .el-cascader {
        width: 350px;
      }
      .el-tabs {
        margin-top: 10px;
      }
      .el-table {
        margin-top: 10px;
        .el-tag {
          margin: 5px;
        }
        .input-new-tag {
          width: 100px;
        }
      }
    }
  }
}
</style>